package ThreadPool.test;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description: 三个线程交叉打印a,b,c,输出100下
 * @date 2022/9/3 11:23
 */
public class ThreadTest1_1 {


    // 用来控制那个线程工作
    private static int whowork = 1;
    // 用来控制打印次数
    private static int num = 1;

    // 定义一个锁对象
    private static Object lock = new Object();


    public static void main(String[] args) throws InterruptedException {
        method1();
    }

    public static void method1() {
        new Thread(()->{
            while(true){
                synchronized (lock) {
                    if(num<=100 && whowork == 1){
                        System.out.println("a");
                        num++;
                        whowork = 2;
                        lock.notifyAll();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                }
            }
        }).start();
        new Thread(()->{
            while(true){
                synchronized (lock) {
                    if(num<=100 && whowork == 2){
                        System.out.println("b");
                        num++;
                        whowork = 3;
                        lock.notifyAll();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                }
            }
        }).start();
        new Thread(()->{
            while(true){
                synchronized (lock) {
                    if(num<=100 && whowork == 3){
                        System.out.println("c");
                        num++;
                        whowork = 1;
                        lock.notifyAll();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                }
            }
        }).start();

    }

}
